js生成文件file对象,blob和file相互转换

您所在的位置:网站首页 js 字符串转换 js生成文件file对象,blob和file相互转换

js生成文件file对象,blob和file相互转换

2023-11-10 20:17| 来源: 网络整理| 查看: 265

有时候会需要将临时的字符串或者表格数据、图片等转换成txt文档

一、 blob转成file

主要是使用file的构造函数

let file = new window.File([blob], filename, filetype)

实际应用示例如下:

let blob = new Blob(['这里是要转换的字符串或者图片等'], {type: "text/plain;charset=utf-8"}) let textContain = transToFile(blob, "文件名", "text/plain") // 这么写是因为文件转换是异步任务 transToFile = async(blob, fileName, fileType) => { return new window.File([blob, fileName, {type: fileType}]) } // 转换完成后可以将file对象传给接口 textContain.then( (res)=> { let file = res console.log(res) })

二、file读或者转成blob 

 使用FileReader let blob = new Blob(['这里是要转换的字符串或者图片等'], {type: "text/plain;charset=utf-8"}) let reader = new FileReader() reader.readAsDataURL(blob) reader.onload = (e)=> { console.log('e就是读取文件返回的对象') }

三、blob转成text文本字符

async() => { return await (new Response(blob).text()) }



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3